﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BSPortal.Data;
using System.Data.Linq;
using System.Threading;
using DedeCMSModel;

namespace DedeSyncWin
{
    #region 用于线程多参数

    /// <summary>
    /// 参数
    /// </summary>
    internal class addParams
    {
        public string txt;
        public Dede_member member;
        public string pass;

    }
    #endregion


    public partial class MForm : Form
    {
        public MForm()
        {
            InitializeComponent();
        }


        #region 用于线程调用方法
        /// <summary>
        /// 用户插入
        /// </summary>
        private void i(object data)
        {
            if (data is addParams)
            {
                addParams ap = (addParams)data;
               // MemberObj.Create(ap.session, ap.member);
            }
        }

        /// <summary>
        /// 用户更新
        /// </summary>
        private void u(object data)
        {
            if (data is addParams)
            {
                addParams ap = (addParams)data;
                //MemberObj.UpdatePSWD(ap.session,ap.txt,ap.pass);
            }
        }

        /// <summary>
        /// 用户停用
        /// </summary>
        /// <param name="data"></param>
        public void d(object data)
        {
            if (data is addParams)
            {
                addParams ap = (addParams) data;
                //MemberObj.Delete(ap.session,ap.txt);
            }
        }
        #endregion

        private IQueryable<Dede_member> members;
        private bool IsExists(string userid)
        {
            //var dbContext = new dedeEntities();
            IQueryable<Dede_member> m = from i in members
                                        where i.Userid == userid
                                        select i;
            if (m.Any())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool CheckRank(string userid, ushort rank)
        {
            //var dbContext = new dedeEntities();
            IQueryable<Dede_member> m = from i in members
                                        where i.Userid == userid
                                        select i;
            if (m.Any())
            {
                return m.FirstOrDefault().Rank == rank || m.FirstOrDefault().Rank >15? true : false;
            }
            else
            {
                return false;
            }
        }

        private string GetPWD(string userid)
        {
            //var dbContext = new dedeEntities();
            IQueryable<Dede_member> m = from i in members
                                              where i.Userid == userid
                                              select i;
            if (m.Any())
            {
                return m.FirstOrDefault().Pwd.Trim();
            }
            else
            {
                return null;
            }

        }

        private Int32 getUnixTimeStamp()
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return Convert.ToInt32(timeStamp);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var dbContext = new dedeEntities();
            textBox1.Text = null;
            //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
            //ISession session = new Configuration().Configure("hibernate.cfg.xml").BuildSessionFactory().OpenSession();

            //Int32 maxid=MemberObj.GetMaxMid(session);
            //获取用户最大ID

            string conn = "server=192.168.150.60;database=Baison_portal;uid=dbmanager;pwd=jyehFuV27FxNQ50tLOV0gglvPZ0=";
            Table<BSPortalUser> bsPortalUsers = BSPortal.Data.GetUserInfo.Get(conn);

            toolStripProgressBar1.Maximum = bsPortalUsers.Count();
            toolStripProgressBar1.Value = 0;
            int num = 0;

            members = from i in dbContext.Dede_members 
                                                  select i;

            foreach (BSPortalUser portalUser in bsPortalUsers)
            {
                Dede_member m = (from i in dbContext.Dede_members 
                                where i.Userid == portalUser.userid
                                select i).FirstOrDefault();

                bool isExist = IsExists(portalUser.userid).Equals(true);

                if (portalUser.ustate.Equals(false))
                {
                    //用户为停用状态：
                    //1.存在于CMS中，停用CMS用户
                    //2.不存在于CMS中，不做处理；
                    if (isExist)
                    {
                        //MemberObj.Delete(session, portalUser.userid);
                        //addParams para = new addParams(session, portalUser.userid,null,null);
                        //Thread threadd = new Thread(new ParameterizedThreadStart(d));
                        //threadd.Start(para);

                        Dede_member member = (from i in members
                                              where i.Userid == portalUser.userid
                                              select i).FirstOrDefault();
                        member.Userid += "##";
                        member.Rank = 0;
                        member.Spacesta = -1;

                        dbContext.SaveChanges();

                        textBox1.Paste(DateTime.Now + "\tD\t账号:" + portalUser.uname + "停用\t" + System.Environment.NewLine);
                        WriteLog(string.Format("D\t账号:{0}停用\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                        toolStripProgressBar1.Value += 1;
                        num += 1;
                        toolStripStatusLabel1.Text = string.Format("第{0}个用户/共{1}个用户", num, bsPortalUsers.Count());
                        this.Refresh();
                    }
                    else
                    {
                        textBox1.Paste(DateTime.Now + "\tN\t账号:" + portalUser.uname + "无无须处理\t" + System.Environment.NewLine);
                        //WriteLog(string.Format("N\t账号:{0}无须处理\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                        toolStripProgressBar1.Value += 1;
                        num += 1;
                        toolStripStatusLabel1.Text = string.Format("第{0}个用户/共{1}个用户", num, bsPortalUsers.Count());
                        this.Refresh();
                    }

                }
                else if (isExist)
                {
                    //用户存在，对比密码，相同不处理
                    if (portalUser.pwd.Trim().Equals(GetPWD(portalUser.userid)) && CheckRank(portalUser.userid, m.Rank))
                    {
                        textBox1.Paste(DateTime.Now + "\tN\t账号:" + portalUser.uname + "不做处理\t" + System.Environment.NewLine);
                        //WriteLog(string.Format("N\t账号:{0}不做处理\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                        toolStripProgressBar1.Value += 1;
                        num += 1;
                        toolStripStatusLabel1.Text = string.Format("第{0}个用户/共{1}个用户", num, bsPortalUsers.Count());
                        this.Refresh();
                    }
                    //用户存在，对比密码，不相同则更新
                    else
                    {
                        //MemberObj.UpdatePSWD(session, portalUser.userid, portalUser.pwd);
                        //addParams para = new addParams(session, portalUser.userid, null, portalUser.pwd);
                        //Thread threadu = new Thread(new ParameterizedThreadStart(u));
                        //threadu.Start(para);

                        Dede_member member = (from i in members
                                              where i.Userid == portalUser.userid
                                              select i).FirstOrDefault();
                        member.Pwd = portalUser.pwd;
                        member.Rank = (ushort)portalUser.rank;
                        dbContext.SaveChanges();

                        textBox1.Paste(DateTime.Now + "\tU\t账号:" + portalUser.uname + "密码、等级更新" + System.Environment.NewLine);
                        WriteLog(string.Format("U\t账号:{0}密码、等级更新\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                        toolStripProgressBar1.Value += 1;
                        num += 1;
                        toolStripStatusLabel1.Text = string.Format("第{0}个用户/共{1}个用户", num, bsPortalUsers.Count());
                        this.Refresh();
                    }

                }
                else
                {
                    //用户不存在，插入
                    Dede_member member = new Dede_member();
                    member.Mtype = portalUser.mtype;
                    member.Userid = portalUser.userid;
                    member.Uname = portalUser.uname;
                    member.Pwd = portalUser.pwd;
                    member.Sex = portalUser.sex;
                    member.Rank = (ushort)(portalUser.rank);
                    member.Money = (uint)(portalUser.money);
                    member.Email = portalUser.email;
                    member.Scores = ushort.Parse(portalUser.scores);
                    member.Matt = ushort.Parse(portalUser.matt);
                    member.Spacesta = -10;
                    member.Face = "";
                    member.Safequestion = 0;
                    member.Safeanswer = "";
                    member.Joinip = "";
                    member.Loginip = "";
                    member.Exptime = 32767;
                    member.Uptime = getUnixTimeStamp();

                    dbContext.Add(member);
                    dbContext.SaveChanges();

                    try
                    {
                        textBox1.Paste(DateTime.Now + "\tI\t账号:" + portalUser.uname + "插入" + System.Environment.NewLine);
                        WriteLog(string.Format("I\t账号:{0}插入\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                        toolStripProgressBar1.Value += 1;
                        num += 1;
                        toolStripStatusLabel1.Text = string.Format("第{0}个用户/共{1}个用户", num, bsPortalUsers.Count());
                        this.Refresh();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        throw;
                    }
                }

            }

            dbContext.ExecuteNonQuery("UP_MemberInit", CommandType.StoredProcedure, null);
            dbContext.SaveChanges();

            MessageBox.Show("用户同步完成！");

        }

        public void WriteLog(string Log)
        {
            string logPath = AppDomain.CurrentDomain.BaseDirectory;
            if (!Directory.Exists(logPath + @"\log"))
            {
                Directory.CreateDirectory(logPath + @"\log");
            }

            StreamWriter dout = new StreamWriter(string.Format(logPath + @"\log\{0}.log", DateTime.Today.ToString("yyyy-MM-dd")), true);
            dout.Write("{0}\t" + Log + System.Environment.NewLine, System.DateTime.Now);
            dout.Close();
        }
    }
}
